Ext.onReady(function(){
    Ext.QuickTips.init();
    Ext.BLANK_IMAGE_URL = 'ext3.2/resources/images/default/s.gif';
    var gridTitle = '管理员管理';
    var findall = "appUser_all.do";
    var getNewIdUrl = "appUser_newId.do";
    var addMsg = 'appUser_add.do';
    var deleteMsg = 'appUser_delete.do';
    var modifyMsg = 'appUser_modify.do';
    
    var renderTo = 'appuser_grid';
    var seqValue = "app_user_seq"; //序列号名称
    var identityName = "userId"; //主键名称
    var pageSize = 18;
    var gridHeight = 500;
    
    var sm = new Ext.grid.CheckboxSelectionModel();
    var cm = new Ext.grid.ColumnModel([sm, {
        header: "用户ID",
        width: 100,
        dataIndex: 'userId'
    }, {
        header: "用户名",
        width: 100,
        sortable: true,
        dataIndex: 'userName'
    }, {
        header: "密码",
        width: 100,
        dataIndex: 'password'
    }, {
        header: "注册时间",
        width: 100,
        dataIndex: 'accessionTime'
    }, {
        header: "状态",
        width: 100,
        dataIndex: 'status'
    }]);
    
    
    var reader = new Ext.data.JsonReader({
        root: 'rows', //rows : 为服务器端传送过来的记录数值对象
        totalProperty: 'total' //results 为服务器端json传送过来的记录的行数, count(*)运算
    }, ['userId', 'userName', 'password', 'accessionTime', 'status']);
    
    //add handle to deal with add action
    function addHandler(){
        var newId;
        var conn = new Ext.data.Connection();
        conn.request({
            url: getNewIdUrl,
            params: {
                seqName: seqValue
            },
            success: function(resp, opt){
                newId = Ext.util.JSON.decode(resp.responseText).newId;
                openCreateWin(newId);
            },
            failure: function(resp, opt){
                Ext.Msg.alert('Error', '获取新id失败');
            }
        })
    }
    
    // add handle to deal with add action
    var openCreateWin = function(newId){
        var win;
        var f = new Ext.form.FormPanel({
            title: "添加信息",
            height: 200,
            autoWidth: true,
            labelWidth: 75,
            labelAlign: "center",
            frame: true,
            defaultType: 'textfield',
            defaults: {
                width: 300,
                allowBlank: false,
                blankText: '必填字段'
            },
            buttonAlign: 'center',
            items: [{
                fieldLabel: '用户ID',
                name: 'appUser.userId',
                value: newId,
                readOnly: true
            }, {
                fieldLabel: '用户名',
                name: 'appUser.userName'
            }, {
                fieldLabel: '密码',
                name: 'appUser.password'
            }],
            
            buttons: [{
                text: "提交",
                handler: s
            }, {
                text: "重置",
                handler: function(){
                    f.form.reset();
                }
            }]
        
        });
        
        function s(){
            f.form.submit({
                waitTitle: "请稍候",
                waitMsg: "正在提交表单数据，请稍候.......",
                url: addMsg,
                success: function(action, form){
                    Ext.MessageBox.alert('提示信息', '数据已经成功提交！', function close(){
                        win.close();
                        location.replace(location.href);
                    });
                },
                failure: function(f, a){
                    Ext.MessageBox.alert('提示信息', "数据添加失败！");
                }
            });
            
        }
        
        if (!win) {
            win = new Ext.Window({
                title: '信息录入',
                width: 450,
                height: 250,
                x: 100,
                y: 50,
                closeAction: 'close',
                plain: true,
                modal: true,
                items: f
            });
        }
        win.show();
        
    };
    
    // 更新表单
    var updateFormHandler = function(){
        var s = grid.getSelectionModel().getSelected();
        if (!s) 
            return false;
        var win;
        var updateForm = new Ext.form.FormPanel({
            title: "修改信息",
            height: 200,
            autoWidth: true,
            labelWidth: 75,
            labelAlign: "center",
            frame: true,
            defaultType: 'textfield',
            defaults: {
                width: 300,
                allowBlank: false,
                blankText: '必填字段'
            },
            buttonAlign: 'center',
            items: [{
                fieldLabel: '用户ID',
                name: 'appUser.userId',
                value: s.get("userId"),
                readOnly: true
            }, {
                fieldLabel: '用户名',
                name: 'appUser.userName',
                value: s.get("userName")
            }, {
                fieldLabel: '密码',
                name: 'appUser.password',
                value: s.get("password")
            }],
            
            buttons: [{
                text: "提交",
                handler: updateSubmit
            }, {
                text: "重置",
                handler: function(){
                    updateForm.form.reset();
                }
            }]
        });
        
        function updateSubmit(){
            updateForm.form.submit({
                waitTitle: "请稍候",
                waitMsg: "正在提交表单数据，请稍候.......",
                url: modifyMsg,
                success: function(action, form){
                    Ext.MessageBox.alert('提示信息', '数据已经成功提交！', function close(){
                        win.close();
                        location.replace(location.href); // 重新载入数据
                    });
                },
                failure: function(f, a){
                    Ext.MessageBox.alert('提示信息', "数据添加失败！");
                }
            });
            
        }
        
        if (!win) {
            win = new Ext.Window({
                title: '信息更改',
                width: 450,
                height: 250,
                x: 100,
                y: 50,
                closeAction: 'close',
                plain: true,
                modal: true,
                items: updateForm
            });
        }
        win.show();
    }
    
    //角色分配
    function assginRoleHandler(){
        var conn = new Ext.data.Connection();
        conn.request({
            url: 'appRole_getRoleListForCheckbox.do',//获取角色列表
            method: 'POST',
            success: function(resp, opt){
                var roleListStr = Ext.util.JSON.decode(resp.responseText).roleListStr;
                //openAssignWin(roleListStr);
				fetchCurrentUsersRoles(roleListStr);
            },
            failure: function(resp, opt){
                Ext.Msg.alert('Error', '获取角色列表失败');
            }
        })
    }
    
	function fetchCurrentUsersRoles(roleListStr) {
		var s = grid.getSelectionModel().getSelected();
        if (!s) 
            return false;
		var conn = new Ext.data.Connection();
        conn.request({
            url: 'appUser_userOwnRoles.do',//获取角色列表
            method: 'POST',
			params: {
				userId:s.get('userId')
			},
            success: function(resp, opt){
                var userOwnRoleIdList = Ext.util.JSON.decode(resp.responseText).userOwnRoleIdList;
                //alert(userOwnRoleIdList);
				openAssignWin(roleListStr, userOwnRoleIdList);
            },
            failure: function(resp, opt){
                Ext.Msg.alert('Error', '获取角色列表失败');
            }
        })
	}
	
	
    function openAssignWin(roleListStr, userOwnRoleIdList){
        var s = grid.getSelectionModel().getSelected();
        if (!s) 
            return false;
        var win;
        var f = new Ext.form.FormPanel({
            title: "角色分配",
            height: 200,
            autoWidth: true,
            labelWidth: 75,
            labelAlign: "center",
            frame: true,
            defaultType: 'textfield',
            defaults: {
                width: 300
            },
            buttonAlign: 'center',
            items: [{
                fieldLabel: '用户ID',
                value: s.get('userId'),
                name: 'assignUserId',
                readOnly: true
            }, {
                fieldLabel: '用户名',
                value: s.get('userName'),
                readOnly: true
            }, {
                xtype: 'checkboxgroup',
                fieldLabel: '角色',
                columns: 3,
                items: Ext.decode(roleListStr)
            }],
            
            buttons: [{
                text: "提交",
                handler: s1
            }, {
                text: "重置",
                handler: function(){
                    f.form.reset();
                }
            }]
        });
        function s1(){
            f.form.submit({
                waitTitle: "请稍候",
                waitMsg: "正在提交表单数据，请稍候.......",
                url: 'appUser_assignRole.do',
                success: function(action, form){
                    Ext.MessageBox.alert('提示信息', '数据已经成功提交！', function close(){
                        win.close();
                    });
                },
                failure: function(f, a){
                    Ext.MessageBox.alert('提示信息', "数据添加失败！");
                }
            });
            
        }
        if (!win) {
            win = new Ext.Window({
                title: '信息录入',
                width: 450,
                height: 250,
                x: 100,
                y: 50,
                closeAction: 'close',
                plain: true,
                modal: true,
                items: f
            });
        }
        win.show();
		
		//设置用户已有的角色
		if(roleOwnFunIdList == null || roleOwnFunIdList == "") return ;
		var roleIds = userOwnRoleIdList.split(',');
		for(var i = 0; i < roleIds.length; i++) {
			document.getElementById("role"+roleIds[i]).checked = "checked";
		}
    }
    
    //-------------------------下面无需改动-----------------------------------------------------------
    
    var store = new Ext.data.Store({
        url: findall,
        reader: reader
    });
    store.load({
        params: {
            start: 0,
            limit: pageSize
        }
    });
    
    
    var grid = new Ext.grid.GridPanel({
        renderTo: renderTo,
        frame: true,
        title: gridTitle,
        autoScroll: true,
        width: "auto",
        height: gridHeight,
        store: store,
        sm: sm,
        cm: cm,
        tbar: [{
            text: ' 增加 ',
            handler: function(){
                addHandler()
            } //deal add
        }, {
            ref: '../removeBtn',
            text: ' 删除 ',
            disabled: true,
            handler: function(e){
                delHandler(e)
            } //处理删除函数 
        }, {
            ref: '../updateBtn',
            text: ' 修改 ',
            disabled: true,
            handler: function(){
                updateFormHandler();
            }
        }, {
            ref: '../roleAssignBtn',
            text: ' 角色分配 ',
            disabled: true,
            handler: function(){
                assginRoleHandler();
            }
        }],
        viewConfig: {
            columnsText: "显示/隐藏列",
            sortAscText: "正序排列",
            sortDescText: "倒序排列"
        },
        bbar: new Ext.PagingToolbar({
            pageSize: pageSize,
            store: store,
            displayInfo: true,
            afterPageText: ' 共 {0} 页',
            beforePageText: '页 ',
            firstText: '第一页 ',
            prevText: '前一页',
            nextText: '下一页',
            lastText: '最后一页',
            refreshText: '刷新',
            displayMsg: '显示第 {0} 条到 {1} 条记录，一共 {2} 条',
            emptyMsg: "没有记录"
        })
    
    });
    
    grid.getSelectionModel().on('selectionchange', function(sm){
        grid.removeBtn.setDisabled(sm.getCount() < 1);
        grid.updateBtn.setDisabled(sm.getCount() != 1);
        grid.roleAssignBtn.setDisabled(sm.getCount() != 1);
    });
    
    //删除的处理函数
    var delHandler = function(e){
        var s = grid.getSelectionModel().getSelections();
        if (!s) 
            return false;
        Ext.Msg.show({
            title: '删除',
            buttons: Ext.MessageBox.YESNOCANCEL,
            msg: '确认删除？',
            fn: function(btn){
        		if(btn == "no" || btn == "cancel") return;
                var ids = "";
                for (var i = 0; i < s.length; i++) { //要删除的记录ID拼串
                    ids = ids + s[i].get(identityName) + ",";
                }
                var conn = new Ext.data.Connection();
                conn.request({
                    url: deleteMsg,
                    params: {
                        delIds: ids
                    },
                    success: function(resp, opt){
                        for (var i = 0; i < s.length; i++) { //把store中相应的记录删掉
                            grid.getStore().remove(s[i]);
                        }
                        store.reload();
                    },
                    failure: function(resp, opt){
                        Ext.Msg.alert('错误', '删除记录失败！');
                    }
                });
            }
        });
    }
});
